/**
 * 报表元数据table
 * @param trData trData
 * @constructor
 */
var ReportParamTable = function (trData) {

    var self = this;
    this.trData = trData || [];
    // 组件类型option数据
    this.controlTypeOption = {
        "1": "下拉框单选",
        "2": "下拉框多选",
        "3": "日期",
        "4": "文本",
        "5": "复选框"
    };
    // 参数类型option数据
    this.dataTypeOption = {
        "1": "字符串",
        "2": "浮点数",
        "3": "整形数",
        "4": "日期"
    };
    // 来源类型option数据
    this.sourceOption = {
        "1": "sql查询",
        "2": "文本",
        "3": "无内容"
    };
    this.paramDataTemplate = _.template('\
        <tr style="display: none;">\
            <td>{{name}}</td>\
            <td>{{title}}</td>\
            <td>{{defaultValue}}</td>\
            <td>{{defaultLabel}}</td>\
            <td>{{controlType}}</td>\
            <td>{{sourceType}}</td>\
            <td>{{dataType}}</td>\
            <td>{{optional}}</td>\
        </tr>\
    ');
    var elementAry = _.map(trData, function (o) {
        return self.paramDataTemplate(o);
    });
    // table id
    this.tableId = 'report_param_table';
    // 私有
    this._tableId = '#report_param_table';
    // 表格模版
    this.view = _.template('\
     <div id="report_param_widget" class="widget-box ui-sortable-handle">\
        <div class="widget-header">\
            <h5 class="widget-title lighter smaller">参数配置</h5>\
            <div class="widget-toolbar">\
                <div class="widget-menu">\
                <a href="#" id="report_param_widget_up"><i class="ace-icon fa fa-chevron-up"></i></a>\
                <a href="#" id="report_param_widget_down"><i class="ace-icon fa fa-chevron-down"></i></a>\
                </div>\
            </div>\
        </div>\
        <div class="widget-body">\
            <div class="widget-main no-padding">\
                <table id="report_param_table" class="table table-bordered">\
                    <thead class="thin-border-bottom">\
                        <tr>\
                            <th>参数名称</th><th>标题</th><th>默认值</th><th>默认标签</th>\
                            <th>表单控件</th><th>内容来源</th><th>参数类型</th><th class="hidden-480">是否必选</th>\
                        </tr>\
                    </thead>\
                    <tbody>{{tbody}}</tbody>\
                </table>\
            </div>\
        </div>\
     </div>\
    ')({tbody: elementAry.join('')});

};
ReportParamTable.prototype = {
    init: function () {
        this.trData = [];
        this.byDelegateEvent();
    },
    /**
     * 获取单选情况下，已选的数据
     * @returns {*}
     */
    getSingleSelectedData: function () {
        var tr = $(this._tableId).children('tbody').children('tr[class=success]');
        if (tr.length > 0) {
            var index = $(tr[0]).index();
            return this.trData[index];
        }
        return null;
    },
    /**
     * 数据转换
     * @param data 数据
     * @returns {*}
     */
    convertData: function (data) {
        data.controlType = this.controlTypeOption[data.controlType];
        data.dataType = this.dataTypeOption[data.dataType];
        data.sourceType = this.sourceOption[data.sourceType];
        data.optional = data.optional ? '是' : '';
    },
    /**
     * 添加一行
     * @param data
     */
    addRow: function (data) {
        this.trData.push(_.clone(data));
        this.convertData(data);
        $(this._tableId).children('tbody').append(this.paramDataTemplate(data)).children('tr:last').fadeIn();
    },
    /**
     * 添加多行
     * @param datas
     */
    addRows: function (datas) {
        datas = datas || [];
        var self = this;
        datas.forEach(function (data) {
            self.addRow(data);
        });
    },
    /**
     * 编辑当前选中行
     * @param data 修改数据
     */
    editRow: function (data) {
        var self = this;
        $(self._tableId).children('tbody').children('tr').each(function (index, item) {
            if ($(item).hasClass('success')) {
                self.trData[$(item).index()] = _.clone(data);
                self.convertData(data);
                $(item)
                    .animate({opacity: '0.2'}, "fast")
                    .animate({opacity: '1'}, "fast", function () {
                        $(this).empty().append($(self.paramDataTemplate(data)).children('td'))
                    });
            }
        });
    },
    /**
     * 删除当前选中行
     */
    removeRow: function () {

        var self = this;
        $(self._tableId).children('tbody').children('tr').each(function (index, item) {
            $(item).hasClass('success') && remove.call(self, $(item).index());
        });

        /**
         * @param rowNumber 行数
         */
        function remove(rowNumber) {
            this.trData.splice(rowNumber, 1);
            $(this._tableId).children('tbody').children('tr:eq(' + rowNumber + ')')
                .fadeOut('fast', function () {
                    $(this).remove();
                });
        }
    },
    /**
     * 添加点击选择功能
     */
    byDelegateEvent: function () {
        var self = this;
        // 绑定table tr点击事件
        var $table = $(this._tableId);
        $table.delegate('tbody>tr', 'click', function (event) {
            // 选择后的高亮颜色
            var $currentTarget = $(event.currentTarget);
            // 取消所有兄弟元素的选择标识，取消所有兄弟元素的高亮
            $currentTarget.siblings().removeData('selected', undefined).removeClass('success');
            !$currentTarget.hasClass('success') && $currentTarget.addClass('success');
            // 触发table 选中事件
            $.Event('report.param.tr.selected', {relatedTarget: $currentTarget});
            $currentTarget.trigger('report.param.tr.selected', [self.getSingleSelectedData()]);
        });
        $('#report_param_widget_down').on('click', function (e) {
            $table.children('tbody').children('tr').each(function (index, item) {
                var $tr = $(item);
                if ($tr.hasClass('success')) {
                    if (null !== $tr.next().html()) {
                        var idx = $tr.index();
                        $.xumf.array.moveDown(self.trData, idx);
                        $tr.insertAfter($tr.next());
                    }
                }
            });
            e.preventDefault();
        });
        $('#report_param_widget_up').on('click', function (e) {
            $table.children('tbody').children('tr').each(function (index, item) {
                var $tr = $(item);
                if ($tr.hasClass('success')) {
                    if (null !== $tr.prev().html()) {
                        var idx = $tr.index();
                        $.xumf.array.moveUp(self.trData, idx);
                        $tr.insertBefore($tr.prev());
                    }
                }
            });
            e.preventDefault();
        });
    }
};
